from dateArg import getDateForZheng
import re

def getAllWords():
    with open('wordsAll.txt', 'r', encoding='utf8') as fp:
        lines = fp.readlines()
        lines = [line for line in lines if line.strip() ]
    
    return lines

def toChunks(ls, size = 7):
    stop = size
    start = 0
    if stop > len(ls):
        return [ls]
    
    chunks = []
    while start < len(ls):
        chunks.append(ls[start:stop])
        start += size
        stop += size

    return chunks



def createWordFile(index, dayWords):
    startDate = '0706'
    m = int(startDate[0:2])
    d = int(startDate[2:])
    newDate = getDateForZheng(m, d, index)
    print(index, newDate)
    writeFile('words%s.txt' % newDate, dayWords)

def halfLen(num, isfloor = False):
    half = num // 2
    if half < num / 2 and not isfloor:
        half += 1
    
    return half

def getThreeLines(words):
    reg = re.compile(r'^[\-a-zA-Z\s]*')

    cnwords = []
    enwords = []
    ybwords = ['-'] * 3

    for word in words:
      matchObj = reg.match(word)
      matched = matchObj.group()
      if not matched:
          print('error: find english word fail', word)
          continue
      else:
          spaceRe = re.compile(r'\s+')
          enwords.append(spaceRe.sub('_', matched.strip()))
          start, stop = matchObj.span()
          cnwords.append(spaceRe.sub('；', word[stop:].strip()))

    threeLines = [' '.join(cnwords) + '\n', ' '.join(enwords) + '\n', ''.join(ybwords) + '\n']
    return threeLines

def writeFile(fname, words):
    lines = []
    with open(fname, 'w', encoding = 'utf8') as fp:
        chunks = toChunks(words, halfLen(len(words)))
          
        firstPart = secondPart = False
        if len(chunks) >= 2:
            firstPart, secondPart = chunks
        elif len(chunks) == 1:
            firstPart = chunks[0]
            
        if firstPart:
          lines.extend(getThreeLines(firstPart))
        if secondPart:
          lines.extend(getThreeLines(secondPart))

        fp.writelines(lines)
    
    print('写入文件 %s 成功' % fname)
    return True

def makeWordFiles():
    lines = getAllWords()
    dayWordsLs = toChunks(lines, 15)
    for index, dayWords in enumerate(dayWordsLs):
        createWordFile(index, dayWords)

if __name__ == '__main__':
    makeWordFiles()